import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
	getMenus
} from '/@/api/system.js'
import {
	getCookieByKey
} from '/@/utils/cookies'
import getPageTitle from '/@/utils/get-page-title'
NProgress.configure({
	showSpinner: false
})

const whiteList = [
	'/login',
]
// function (routers){
// 	let data=[];
// 	// routers.forEach(item=>{
// 	// 	let r ={
// 	// 		path:item.path,
// 	// 		name:item.name,
// 	// 		component: import(item.component),

// 	// 	}
// 	// })
// }

router.beforeEach(async (to, from, next) => {
	console.log('222');
	NProgress.start()
	document.title = getPageTitle(to.meta.title)
	const hasToken = getCookieByKey('vite_token')
	if (hasToken && hasToken !== 'undefined') {
		console.log('2233');
		if (to.path === '/login') {
			next({
				path: '/'
			})
			NProgress.done()
		} else {
			console.log('2233');
			const hasRoles = store.getters.roles && store.getters.roles.length > 0
			console.log('11111',hasRoles);
			if (hasRoles) {
				next()
			} else {
				try {

					const {
						roles
					} = await store.dispatch('user/loginByToken', {})


					let {
						data
					} = await getMenus();



					const accessRoutes = await store.dispatch('permission/generateRoutes', data)
					accessRoutes.forEach(item => {
						router.addRoute(item)
					})
					next({
						...to,
						replace: true
					})
				} catch (error) {
					await store.dispatch('user/resetInfo')
					next(`/login`)
					NProgress.done()
				}
			}
		}
	} else {
		console.log('333');
		// router.addRoute('/version')
		next()
		// if (whiteList.indexOf(to.path) !== -1) {
		// 	next()
		// } else {
		// 	console.log('555');
		// 	next(`/login`)
		// 	NProgress.done()
		// }
	}
})

router.afterEach(() => {
	NProgress.done()
})
